/**
 * 
 */
package com.lvan.service.order;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lvan.bean.BaseException;
import com.lvan.bean.Order;
import com.lvan.bean.Page;
import com.lvan.constant.ValidateRecord;
import com.lvan.dao.mapper.OrderMapper;
import com.lvan.service.AbstractService;
import com.lvan.service.interfaze.order.IOrderService;
import com.lvan.util.InputValidate;

/**
 * @author lvan.he<br>
 *         2013-6-26<br>
 * @version 1.0.0.0
 */
@Service("orderService")
public class OrderService extends AbstractService implements IOrderService {
	private InputValidate<Order> validator = new InputValidate<Order>();
	@Autowired
	private OrderMapper orderMapper;

	@Override
	public void add(Order o) throws BaseException {
		Set<ValidateRecord> constraintViolations = validator.validate(o, true);
		if (!constraintViolations.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			for (ValidateRecord constraintViolation : constraintViolations) {
				sb.append(constraintViolation.getMessage() + "; ");
			}
			throw new BaseException("", REQUEST_PARAM_ERROR, sb.toString());
		}
		orderMapper.add(o);
	}

	@Override
	public void delete(Serializable ids) {
		if (ids != null)
			orderMapper.delete(ids);
	}

	@Override
	public Order getByID(Serializable id) {
		return orderMapper.getByID(id);
	}

	@Override
	public List<Order> query(Order o, Page page) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("order", o);
		params.put("page", page.getPageSql());
		params.put("orderBy", o.convertField2Column());
		page.setTotal(this.count(o));
		return orderMapper.query(params);
	}

	@Override
	public void update(Order o) throws BaseException {
		Set<ValidateRecord> constraintViolations = validator.validate(o, false);
		if (!constraintViolations.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			for (ValidateRecord constraintViolation : constraintViolations) {
				sb.append(constraintViolation.getMessage() + "; ");
			}
			throw new BaseException("", REQUEST_PARAM_ERROR, sb.toString());
		}
		orderMapper.update(o);
	}

	@Override
	public int count(Order o) {
		return orderMapper.count(o);
	}
}
